﻿using Pay.Core;
using Pay.Data;
using Pay.DTO;
using Pay.IService;
using Pay.Service;
using Pay.TO;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Flurl;
using Flurl.Http;
using System.Threading.Tasks;

namespace Pay.Token.Controllers {
    //  [RouteArea("h5"), RoutePrefix("merchant"), AppAuthorize("Member")]
    [AppAuthorize("Member")]
    public class UserController : GeneralController {
        private IMerchantService _merchantService;
        private IUnitOfWork _unitOfWork;
        private ISettingService _settingService;
        private IUserFeedBackService _userFeedBackService;
        private IRedRecordService _iRedRecordService;
        private IAdvertisementService _iAdvertisementService;
        private IShippingAddressService _iShippingAddressService;
        private IOrderService _iOrderService;
        private IOrderModelCache _iOrderModelCache;
        private IRegionService _iRegionService;
        private IArticleService _iArticleService;
        public UserController(IMerchantService merchantService, ISettingService settingService, 
            IRedRecordService redRecordService,IOrderModelCache iOrderModelCache,
            IUserFeedBackService userFeedBackService, IOrderService iOrderService,
            IAdvertisementService advertisementService, IShippingAddressService iShippingAddressService,
            IRegionService iRegionService,  IArticleService iArticleService,IUnitOfWork unitOfWork) {
            _merchantService = merchantService;
            _unitOfWork = unitOfWork;
            _settingService = settingService;
            _userFeedBackService = userFeedBackService;
            _iRedRecordService = redRecordService;
            _iAdvertisementService = advertisementService;
            _iShippingAddressService = iShippingAddressService;
            _iRegionService = iRegionService;
            _iOrderService = iOrderService;
            _iOrderModelCache = iOrderModelCache;
            _iArticleService = iArticleService;
        }
        #region 实名认证
        /// <summary>
        /// 实名认证
        /// </summary>
        /// <returns></returns>
        public ActionResult Authentication() {
            //var member = _merchantService.GetTokenUser(UserId);
            //if(member.is_verify_no_card) return RedirectToAction("Index", "Home");
            //else
            return View();
        }
        [HttpPost]
        public async Task<JsonResult> AuthenticationPost(string Name, string IdCard) {
            var model = new token_cardno_model();
            model.user_name = Name;
            model.card_no = IdCard;
            var result = await _merchantService.VerificationNoCard(model, UserId);
            if (result) {
                return Json(ResultToJson.Json("实名认证成功", true), JsonRequestBehavior.AllowGet);
            } else {
                return Json(ResultToJson.Json<bool>("实名认证失败"), JsonRequestBehavior.AllowGet);
            }

        }
        #endregion
        /// <summary>
        /// 邀请码认证
        /// </summary>
        /// <returns></returns>
        #region  邀请码认证
        public ActionResult SetName() {
            //var member = _merchantService.GetTokenUser(UserId);
            //if (!member.is_verify_invitation_code) return View();
            //else {
            //    return RedirectToAction("Index", "Home");
            //    //if (member.is_verify_no_card) return  RedirectToAction("Index", "Home");
            //    // else return RedirectToAction("Authentication", "User");
            //}
            return View();
        }
        [HttpPost]
        public JsonResult SetNamePost(string Code, string NickName) {

            var model = new token_invitation_code_model();
            model.invitation_code = Code;
            model.nick_name = NickName;
            if (_merchantService.InvitationCode(model, UserId)) {
                return Json(ResultToJson.Json("邀请码认证成功", true), JsonRequestBehavior.AllowGet);
            } else {
                return Json(ResultToJson.Json("邀请码认证失败", false), JsonRequestBehavior.AllowGet);
            }
        }
        #endregion

        #region  用户反馈
        [HttpPost, ValidateInput(true)]
        public JsonResult SaveFeedback(string Content, string Contact) {
            var model = new user_feedback_dto();
            model.createtime = DateTime.Now;
            model.usercontact = Contact;
            model.userid = UserId;
            model.user_feedback_content = Content;
            if (_userFeedBackService.Add(model) > 0) {
                return Json(new { msg = "操作成功" }, JsonRequestBehavior.AllowGet);
            } else {
                return Json(new { msg = "系统异常" }, JsonRequestBehavior.AllowGet);
            }

        }
        public ActionResult Sucess() { return View(); }
        public ActionResult UserFeedBack() {

            return View();
        }
        #endregion
        [HttpPost]
        public JsonResult UpdateNickName(string Name) {
            var result = _merchantService.SaveUserNickName(Name, UserId, t_RequestMethod.merchant_no);
            if (result) {
                return Json(ResultToJson.Json("修改成功", true), JsonRequestBehavior.AllowGet);
            } else {
                return Json(ResultToJson.Json("修改失败", false), JsonRequestBehavior.AllowGet);
            }

        }
        #region 用户中心
        public ActionResult UserInfo() {
            var user = _merchantService.GetTokenUser(UserId);
            if (user != null) {
                ViewData["user"] = user;
            } else {
                ViewData["user"] = new token_user_info();
            }
            ViewBag.img_url = RequestMethod.token_imgurl;
            return View();
        }
        #endregion
        #region 我的资产
        public ActionResult MyAsset() {
            var data = _iRedRecordService.GetUser(UserId);
            ViewData["data"] = data;
            return View();

        }
        [AllowAnonymous]
        public ActionResult Ecology() {
            return View();
        }
        public PartialViewResult _MyAsset(RedQuery query) {
            query.merchant_id = UserId;
            var list = _iRedRecordService.GetUserRedRecords(query);
            ViewBag.type = query.type;
            return PartialView(list);
        }
        #endregion
        #region 收货地址
        /// <summary>
        /// 收货地址
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [AllowAnonymous]
        public ActionResult Adress(long id) {
            bool is_seas = false;
            var adress = new shipping_address_dto();
            if (UserId > 0) {
                adress = _iShippingAddressService.GetByAddressId(id);
                if (adress == null) adress = new shipping_address_dto();
                if (adress.user_id != UserId) adress = new shipping_address_dto();
                var cache_model = _iOrderModelCache.GetOrderModelCache<token_check_out_model>(UserId.ToString());
                is_seas = (cache_model != null ? cache_model.is_seas : true);
            } else {
                //todo：匿名购买取缓存收货地址对象
                string cache_no = GetCookieValue("cache_no");
                var cache_model = _iOrderModelCache.GetOrderModelCache<token_check_out_model>(cache_no);
                if (cache_model == null)
                    adress = new shipping_address_dto();
                if (id > 0) {
                    var cache_shipping = cache_model.shipping[id];
                    adress.region_name = _iRegionService.GetRegionNames(cache_shipping.region_id);
                    adress.address = cache_shipping.address;
                    adress.phone = cache_shipping.phone;
                    adress.ship_to = cache_shipping.shipto;
                    adress.real_name = cache_shipping.real_name;
                    adress.id_card = cache_shipping.id_card;
                }
                is_seas = cache_model.is_seas;
            }
            ViewBag.isLogin = (UserId > 0 ? true : false);
            ViewBag.isSeas = is_seas;
            return View(adress);
        }
        /// <summary>
        /// 新增编辑收货地址
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost, AllowAnonymous]
        public JsonResult SaveAdress(shipping_address_dto model) {
            if (!ModelState.IsValid)
                return Json(ResultToJson.Json<bool>(ModelError));

            if (UserId > 0) {
                model.user_id = UserId;
                model.card_negative = model.card_positive = string.Empty;
                if (string.IsNullOrEmpty(model.id_card) || string.IsNullOrEmpty(model.real_name)) {
                    if (model.id > 0) {
                        var item = _iShippingAddressService.Get(model.id);
                        model.id_card = item.id_card;
                        model.real_name = item.real_name;
                    } else {
                        var auth = _merchantService.GetAuth(UserId);
                        if (auth != null) {
                            model.id_card = auth.id_card;
                            model.real_name = auth.account_name;
                        } else
                            model.id_card = model.real_name = string.Empty;
                    }
                }
                int result = 0;
                if (model.id == 0)
                    result = _iShippingAddressService.Add(model);
                else
                    result = _iShippingAddressService.Update(model);
            } else {
                //todo：匿名购买收货地址写缓存
                string cache_no = GetCookieValue("cache_no");
                var cache_model = _iOrderModelCache.GetOrderModelCache<token_check_out_model>(cache_no); ;
                if (cache_model == null)
                    throw new ServerErrorException("缓存失效");
                cache_model.shipping_address_id = 1;
                cache_model.shipping.Clear();
                cache_model.shipping.Add(cache_model.shipping_address_id, new shippingaddress_dto {
                    id = cache_model.shipping_address_id.Value,
                    shipto = model.ship_to,
                    phone = model.phone,
                    id_card = model.id_card,
                    real_name = model.real_name,
                    region_id = model.area_id > 0 ? model.area_id : model.city_id,
                    address = model.address
                });
                model.id = cache_model.shipping_address_id.Value;
                _iOrderModelCache.SetOrderModelCache(cache_model, cache_no);
                if (cache_model.is_seas) {
                    if (model.ship_to != model.real_name)
                        return Json(ResultToJson.Json<string>("收货人和真实姓名必须一致"));
                }
            }

            return Json(ResultToJson.Json(1000, "保存成功", new { isLogin = (UserId > 0 ? true : false), addressId = model.id }));
        }
        /// <summary>
        /// 删除地址
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult DelAdress(long id) {
            var result = _iShippingAddressService.DeleteAdress(id);
            return Json(ResultToJson.Json(result > 0 ? 1000 : 1001, result > 0 ? "删除成功" : "删除失败", result > 0));
        }
        [HttpPost]
        public JsonResult UpdateDefault(long id) {
            var result = _iShippingAddressService.UpdateDefault(id, UserId);
            return Json(ResultToJson.Json(result > 0 ? 1000 : 1001, result > 0 ? "更新成功" : "更新失败", result > 0));
        }
        /// <summary>
        /// 区域
        /// </summary>
        /// <returns></returns>
        [HttpGet, AllowAnonymous]
        public JsonResult GetRegion() {
            var list = _iRegionService.GetAll(0, 3, false).ToList();
            return Json(ResultToJson.Json("获取成功", list), JsonRequestBehavior.AllowGet);
        }
        /// <summary>
        /// 我的地址管理
        /// </summary>
        /// <returns></returns>
        public ActionResult MyAdress() {
            var list = _iShippingAddressService.GetAddressByUser(UserId).ToList();
            return View(list);
        }
        #endregion
        [AllowAnonymous]
        public ActionResult My() {
            if (UserId == 0) {
                ViewData["user"] = new token_user_info();
            } else {
                ViewData["user"] = _merchantService.GetTokenUser(UserId);
            }
            merch_advertisement_query_type query = new merch_advertisement_query_type();
            query.position_type = (int)EAdvertisementPositionType.MyPage;
            ViewData["ad"] = (_iAdvertisementService.AppGetAdvertisementList(query) ?? new List<ad_dto>()).FirstOrDefault();
            ViewData["site_img"] = RequestMethod.token_imgurl;
            return View();
        }
        public async Task<JsonResult> Upload() {
            string path = base.Upload("profile", "upload");
            var member = _merchantService.Get(UserId);
            if (!string.IsNullOrEmpty(member.photo) && !string.IsNullOrEmpty(path) && member.photo != path) {
                var data = new t_delete_file_model();
                data.file_names.Add(new file_name_item { file_name = member.photo });
                data.method = t_RequestMethod.DELETE_FILE;
                var d_result = await ChannelApi.Current.PostApi<result_base>(data);
            }
            bool result = false;
            if (!string.IsNullOrEmpty(path)) {
                member.photo = path;
                result = _merchantService.UpdateUser(member);
            }
            return Json(ResultToJson.Json(new { result = result, path = RequestMethod.token_imgurl + path }), JsonRequestBehavior.AllowGet);
        }
        #region 帮助中心
        /// <summary>
        /// 帮助中心
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        public ActionResult Help() {
         var result=_iArticleService.GetRecommendArticles();
            var app_setting = _settingService.GetTokenSetting().app;
            ViewBag.app_setting = app_setting;
            return View(result);
        }
        /// <summary>
        /// 更多问题
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        public ActionResult HelpMore() {
            var app_setting = _settingService.GetTokenSetting().app;
            ViewBag.app_setting = app_setting;
            return View();
        }
        [AllowAnonymous]
        public ActionResult HelpSearch(string keyword) {
            return View();
        }
        [AllowAnonymous]
        public PartialViewResult _Help(ArticleQuery query) {
            query.type = 1;
            query.status = ArticleStatus.Normal;
            query.is_highlight = true;
           var result=  _iArticleService.GetArticles(query);
            return PartialView(result);
        }
        /// <summary>
        /// 客服电话
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        public ActionResult _HelpService() {
            var app_setting = _settingService.GetTokenSetting().app;
            ViewBag.app_setting = app_setting;
            return PartialView(app_setting);
        }
        /// <summary>
        /// 文章详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [AllowAnonymous]
        public ActionResult HelpDetail(long id) {
            var model = _iArticleService.GetArticle(id);
            var app_setting = _settingService.GetTokenSetting().app;
            ViewBag.app_setting = app_setting;
            return View(model);
        } 
        #endregion
        public ActionResult InviteList() {
            return View();
        }
        public PartialViewResult _InviteList(MerchantChildQuery query) {
            query.merchant_id = UserId;
          var list=  _merchantService.GetOneChild(query);
            return PartialView(list);
        }
    }
}
